package o2o.web.actions.shop;

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.shop.ShopMemory;
import o2o.cache.shop.SpecialShopListMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.DataDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.shop.SPECIAL_SHOP_LIST_TYPE;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.shop.SpecialShopListInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.shop.ShopInfoVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

//用户收藏的店铺
@Controller
public class SpecialShopListAction {

    // 特殊店铺列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/special/shop/list")
    @ResponseBody
    public String shop_like_list(String token, Integer type, String city, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        // 获取不同类型店铺
        if (null == type) {
            type = SPECIAL_SHOP_LIST_TYPE.ALL_COUNTRY;// 默认全国
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        HashSet<Long> shopSet = SpecialShopListMemory.getInstance().listOfType(type);
        List<ShopInfoVO> voList = new ArrayList<>();
        for (Long shopId : shopSet) {
            ShopInfo info = ShopMemory.getInstance().getShopById(shopId);
            if (null == info) {
                continue;
            }
            ShopInfoVO vo = new ShopInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(info, vo);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            HashSet<SpecialShopListInfo> specialSet = SpecialShopListMemory.getInstance().listOfShopId(vo.getId());
            if (null != specialSet && specialSet.size() > 0) {
                vo.setSpecialShopInfos(new ArrayList<>(specialSet));
            }

            voList.add(vo);
        }

        if (ValidateUtil.isAbsList(voList)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && ValidateUtil.isAbsList((pageList.list))) {
                return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
            }
        }


        return AjaxResult.successResult(0, 0, null);
    }

    // 添加特殊店铺
    @RequestMapping(method = RequestMethod.POST, value = "/admin/special/shop/add")
    @ResponseBody
    public String shop_like_add(String token, SpecialShopListInfo info, String types) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == info || ValidateUtil.isNotID(info.getShopId())) {
            return AjaxResult.errorResult("请先选择要操作的店铺");
        }


        // 先清除之前的类型
        ResultInfo reInfo = deleteShopSpecial(info.getShopId(), user.getUsername());
        if (null == reInfo) {
            return AjaxResult.errorResult("添加失败，请稍后再试1");
        } else {
            if (!reInfo.isSuccess()) {
                return AjaxResult.errorResult(reInfo.getError());
            }
        }


        if (null == types) {// 默认全国
            types = SPECIAL_SHOP_LIST_TYPE.ALL_COUNTRY + "";
        }

        String[] typeArr = types.split(",");
        if (typeArr.length > 0) {
            for (int i = 0; i < typeArr.length; i++) {
                if (ValidateUtil.isNull(typeArr[i])) {
                    continue;
                }
                info.setListType(Integer.parseInt(typeArr[i]));
                ResultInfo resultInfo = add(info, user.getUsername());
                if (null == resultInfo) {
                    return AjaxResult.errorResult("添加失败，请稍后再试");
                } else {
                    if (!resultInfo.isSuccess()) {
                        return AjaxResult.errorResult(resultInfo.getError());
                    }
                }
            }
        } else {
            info.setListType(Integer.parseInt(types));
            ResultInfo resultInfo = add(info, user.getUsername());
            if (null == resultInfo) {
                return AjaxResult.errorResult("添加失败，请稍后再试。");
            } else {
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            }
        }

        // 处理缓存
        SpecialShopListMemory.getInstance().reload();
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_SPECIAL_RELOAD);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return AjaxResult.successResult();
    }


    // 删除特殊店铺
    @RequestMapping(method = RequestMethod.POST, value = "/admin/special/shop/delete")
    @ResponseBody
    public String shop_like_delete(String token, String ids,
                                   String shopIds, Integer listType) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(ids) && (ValidateUtil.isNull(shopIds) && ValidateUtil.isNotAbsInteger(listType))) {
            return AjaxResult.errorResult("请先选择要删除的");
        }

        if (ValidateUtil.isNotNull(ids)) {
            // 按id删
            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SPECIAL_SHOP_LIST)
                    .append(" set delFlag = 1,updateUser='").append(user.getUsername()).append("' where delFlag = 0 and id in (").append(ids).append(")");

            try {
                DataDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("删除失败，请稍后再试");
            }
        } else {
            // 按id删
            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SPECIAL_SHOP_LIST)
                    .append(" set delFlag = 1,updateUser='").append(user.getUsername()).append("' where delFlag = 0 and listType = ").append(listType).append(" shopId in (").append(shopIds).append(")");

            try {
                DataDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("删除失败，请稍后再试");
            }
        }


        // 处理缓存
        SpecialShopListMemory.getInstance().reload();
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_SPECIAL_RELOAD);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return AjaxResult.successResult();
    }

    // 增加一个
    private ResultInfo add(SpecialShopListInfo info, String opUsername) {
        info.setCreateTime(DateUtils.getCurrTime());
        info.setCreateUser(opUsername);

        try {
            DataDaoSql.getInstance().insertObj(PojoTables.SPECIAL_SHOP_LIST, info);
        } catch (SQLException e) {
            e.printStackTrace();
//            return AjaxResult.errorResult("添加失败，请稍后再试");
            return new ResultInfo("添加失败，请稍后再试");
        }

        return new ResultInfo();
    }


    // 删除所有的类型
    private ResultInfo deleteShopSpecial(Long shopId, String opUsername) {
        if (ValidateUtil.isNotID(shopId)) {
            return new ResultInfo("店铺Id不能为空");
        }
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.SPECIAL_SHOP_LIST)
                .append(" set delFlag = 1,updateUser='").append(opUsername).append("' where delFlag = 0 and shopId = ").append(shopId);

        try {
            DataDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("删除失败，请稍后再试");
        }

        return new ResultInfo();
    }

}

